import { defineComponent, Teleport, ref, reactive, computed, watchEffect, onMounted, watch, onUnmounted } from "vue";
import styles from "./AccidentInsurePage.module.less";
import LIcon from "@/components/public/lIcon/lIcon";
import { EditOutlined, BellFilled, CopyOutlined, UserOutlined, DownloadOutlined, CloseCircleOutlined, CheckSquareFilled, ExclamationCircleFilled, LoadingOutlined } from "@ant-design/icons-vue";
import PlanEdit from "./components/PlanEdit/PlanEdit";
import ExamplePopup from "./components/ExamplePopup/ExamplePopup";
import _ from "lodash";
import { message, Modal } from "ant-design-vue";
import validateInstance from "@/libs/validate/validate";
// import text_describe from "./text_describe";
import Terms from "./components/Terms/Terms";
import ClientNotice from "./components/ClientNotice/ClientNotice";
import BatchImport from "./components/BatchImport/BatchImport";
import SmartPaste from "./components/SmartPaste/SmartPaste";
import DraftPopup from "./components/DraftPopup/DraftPopup";
import { useRoute, useRouter } from "vue-router";
import { imgPath } from "@/common/utils";
import util from "./util";
import { useStore as useUserStore } from "@/store/user";
import { $calculatePayMoney, $creatGroup, $importPeople, $onlinePay, $pay } from "@/api/order/order";
import { $getProductDetail } from "@/api/product/product";
import { $orderCreatGroup } from "@/api/accidentInsurePage/accidentInsurePage";
import eventBus from "@/common/mitt";
import TermPact from "./components/termPact/termPact";
import { $userAuthStatus } from "@/api/account/account";
import { $loginUser } from "@/api/login/login";
import { $aliStsToken, $getGroup } from "@/api/common/common";
import { record } from 'rrweb';
import { useStore as useScreenRecordingStore } from '@/store/screenRecording';
import to from "await-to-js";
import pako from "pako";
import dayjs from 'dayjs';
const OSS = require('ali-oss');
var OssCredit: any;
var OssClient: any;
export default defineComponent({
  name: 'AccidentInsurePage',
  setup() {
    const router = useRouter();
    const route = useRoute();
    const userStore = useUserStore();
    const screenRecordingStore = useScreenRecordingStore();
    const statement_read = ref(true);
    const insured_default = {
      key: '',
      real_name: '',
      id_type: '111',
      id_no: '',
      sex: '',
      birthday: '',
    }
    const form = ref({
      product_id: Number(route.query.product),//id
      name: '',//保险名称
      issuing_company: '中国平安财产保险有限公司',//出单公司
      start_date: String(route.query.start_date) as any,//起保日期
      start_time: '',
      end_date: String(route.query.end_date) as any,//止保日期
      end_time: '23:59',
      count: 1,//保险份数
      tour_route: String(route.query.travel_route),//旅游路线
      tour_group_no: String(route.query.travel_no),//旅游团编号
      id_type: 111,  //投保人类型
      realname: '',//投保人姓名
      mobile: '',//投保人手机号
      idcard: '',//投保人身份证号
      sex: '',//投保人性别
      send_sms: false,//出单短信通知
      travel_agency_name: '',//企业名称
      business_contacts: '',//企业联系人
      code: '',//统一社会信用代码
      contract_mobile: '', //企业手机号
      insured_list: [] as any[],//被保人列表
      status: 0,  //用户状态
      disabled: false,
      countryCode: String(route.query.countryCode), //国家代码
    })

    const text_describe = ref("" as string);
    const termsState = ref([] as any[]);
    const noticeTitleState = ref("" as string);
    const noticeState = ref("" as string);
    const recordFunc = ref(null as any);

    const crateWeb = () => {
      let events: any[] = [];
      recordFunc.value = record({
        emit(event) {
          // 用任意方式存储 event
          events.push(event);
          screenRecordingStore.addEvents(events, 'order');
        }
      })
    }
    // 获取oss配置
    const initOssClient = () => {
      return new Promise(function (resolve, reject) {
        $aliStsToken().then((res: any) => {
          if (res.code === 200) {
            OssCredit = res.data
            OssClient = {
              objectName: OssCredit.objectName,
              domain: OssCredit.domain,
              instance: new OSS({
                accessKeyId: OssCredit.AccessKeyId,
                accessKeySecret: OssCredit.AccessKeySecret,
                stsToken: OssCredit.SecurityToken,
                endpoint: OssCredit.endpoint,
                bucket: OssCredit.bucket
              })
            }
            resolve(OssClient)
          }
        }).catch(() => {
          resolve(null)
        })
      })
    }

    const saveScreenRecord = async () => {
      // message.loading('记录提交中...')
      const hide = message.loading('记录提交中...', 0);
      const event = encodeURIComponent(JSON.stringify(screenRecordingStore.events.order));
      const ossClientInstance: any = await initOssClient();
      const [err, res]: any = await to(ossClientInstance.instance.multipartUpload(ossClientInstance?.objectName, new Blob([event], { type: 'text/plain' })));
      hide();
      return [err, ossClientInstance];
    }

    onMounted(() => {
      crateWeb();
      // statement_read.value = false;
      if (isToday(form.value.start_date)) {
        form.value.start_time = 'T + 1h'
      } else {
        form.value.start_time = '00:00'
      }
      $getProductDetail({ product_id: Number(route.query.product) }).then((res: any) => {
        form.value.name = res?.data?.product.name || "";
        text_describe.value = res?.data?.product.insurance?.term?.pro_term || "";
        termsState.value = res?.data?.product.insurance?.term_rel || [];
        noticeTitleState.value = res?.data?.product.insurance?.client_notice?.title || "";
        noticeState.value = res?.data?.product.insurance?.client_notice?.content || "";
        let list: any[] = res?.data?.product.insurance?.term_pact;
        terms_list.term_pact = list.sort((a, b) => a.sort - b.sort)
      })
      $userAuthStatus().then((res: any) => {
        form.value.status = res?.data?.status || '';
        if (Number(res?.data?.status) === 20) {
          form.value.id_type = 989;
          $loginUser().then((res: any) => {
            form.value.travel_agency_name = res.data?.agency?.name || '';
            form.value.code = res.data?.agency?.code || '';
            form.value.business_contacts = res.data?.agency?.contact_person || '';
            form.value.contract_mobile = res.data?.agency?.contact_phone || '';
            form.value.disabled = true;
          })
        }
      })
      form.value.insured_list.push({ ..._.cloneDeep(insured_default), key: new Date().getTime() })
    })
    watchEffect(() => {
      form.value.insured_list.forEach(x => {
        if (x.real_name && x.id_type === '111' && validateInstance.test(x.id_no, "idcard")) {
          let birthday = x.id_no.slice(6, 10) + '-' + x.id_no.slice(10, 12) + '-' + x.id_no.slice(12, 14);
          x.birthday = birthday;
          let sex = Number(x.id_no.slice(16, 17));
          x.sex = (sex % 2 === 1) ? 1 : 2;
        }
      })
    })

    // watch(() => form.value.insured_list, (nv, ov) => {
    //   console.log(nv);
    //   if (nv !== ov) {
    //     pay_type.total_premium = 0;
    //     terms_list.checked = false;
    //     console.log('数组发生变化')
    //     // $calculatePayMoney({
    //     //   product_id: form.value.product_id,
    //     //   start_date: form.value.start_date,
    //     //   start_hour: 0,
    //     //   end_date: form.value.end_date,
    //     //   end_hour: 24,
    //     //   insured: form.value.insured_list.map(x => {
    //     //     return {
    //     //       real_name: x.real_name,
    //     //       id_type: x.id_type,
    //     //       id_no: x.id_no,
    //     //       sex: x.sex,
    //     //       birthday: x.birthday,
    //     //     }
    //     //   })
    //     // }).then((res: any) => {
    //     //   pay_type.total_premium = res?.data?.sum_premium || 0;
    //     // })
    //   }
    // })

    watch(() => userStore.token, (nv) => {
      if (!nv) {
        message.error('登录已失效，请重新登录进行投保');
        router.push('/GroupList');
        const dom: any = document.getElementById("app");
        dom.scrollTop = 0;
      }
    }, {
      immediate: true,
      deep: true,
    })

    const state = reactive({
      page: 1,
      defaultPageSize: 50,
    })
    const during_date = computed(() => {
      if (form.value.start_date && form.value.end_date) {
        return Math.ceil(Math.abs(new Date(form.value.end_date).getTime() - new Date(form.value.start_date).getTime()) / (24 * 60 * 60 * 1000)) + 1;
      } else {
        return 0;
      }
    })

    const isToday = (e: string) => {
      return new Date().toDateString() === new Date(e).toDateString();
    }

    const travel_agency_name_check = async (_rule: any, value: string) => {
      if (value === '') {
        return Promise.reject('请输入旅行社名称!');
      }
    }

    const realname_check = async (_rule: any, value: string) => {
      if (value === '') {
        return Promise.reject('请输入联系人姓名!');
      }
    }
    const mobile_check = async (_rule: any, value: string) => {
      console.log(value)
      if (value === '') {
        return Promise.reject('请输入手机号!');
      } else if (!validateInstance.test(value, "phone")) {
        return Promise.reject('手机号格式不正确!');
      }
    }
    const idcard_check = async (_rule: any, value: string) => {
      if (!validateInstance.test(value, "idcard")) {
        return Promise.reject('请输入正确的身份证信息!');
      }
    }
    const code_check = async (_rule: any, value: string) => {
      if (value === '') {
        return Promise.reject('请输入统一社会信用代码!');
      }
    }
    // 表单验证
    const rules = {
      realname: [{ required: true, validator: realname_check, trigger: 'change' }],
      mobile: [{ required: true, validator: mobile_check, trigger: 'change' }],
      idcard: [{ required: true, validator: idcard_check, trigger: 'change' }],
    }
    const enterpriseRules = {
      travel_agency_name: [{ required: true, validator: travel_agency_name_check, trigger: 'change' }],
      code: [{ required: true, validator: code_check, trigger: 'change' }],
      contract_mobile: [{ required: true, validator: mobile_check, trigger: 'change' }],
      business_contacts: [{ required: true, validator: realname_check, trigger: 'change' }]
    }

    const radioChange = () => {
      if (form.value.id_type === 989) {
        if (!(form.value.status === 20)) {
          form.value.id_type = 111;
          message.error('企业未认证或未通过，无法进行企业投保');
          return;
        }
      }
    }
    // 投保人表单
    const Applicant = () => (
      <div class={styles.applicant}>
        <div class={styles['applicant-title']}>
          <span>投保人信息</span>
          <div class={styles['applicant-type']}>
            <a-radio-group
              v-model:value={form.value.id_type}
              name="radioGroup"
              onChange={() => { radioChange() }}
            >
              <a-radio value={0}>自动</a-radio>
              <a-radio value={111}>个人</a-radio>
              <a-radio value={989}>企业</a-radio>
            </a-radio-group>
          </div>
        </div>
        <div class={styles['display_holder']}>
          <div class={styles['policy_holder']}>
            {
              <a-form model={form.value} v-show={form.value.id_type === 111} rules={rules} label-col={{ style: { width: '120px' } }} wrapper-col={{ span: 28 }}>
                <a-form-item required label="联系人姓名" name="realname">
                  <a-input style={{ width: '210px' }} v-model:value={form.value.realname} />
                </a-form-item>
                <div style={{ display: 'flex' }}>
                  <a-form-item wrapper-col={{ span: 12 }} label="联系人手机号" name="mobile">
                    <a-input style={{ width: '210px' }} v-model:value={form.value.mobile} maxlength={11} />
                  </a-form-item>
                  {/* <a-form-item wrapper-col={{ span: 5 }} label="出单短信通知" name="send_sms">
                    <a-switch v-model:checked={form.value.send_sms} checked-children="是" un-checked-children="否" />
                  </a-form-item> */}
                </div>
                <a-form-item wrapper-col={{ span: 14 }} label="证件号/身份证号" name="idcard">
                  <a-input style={{ width: '210px' }} v-model:value={form.value.idcard} maxlength={18} />
                </a-form-item>
              </a-form>
            }
            {
              <a-form model={form.value} v-show={form.value.id_type === 989} rules={enterpriseRules} label-col={{ style: { width: '120px' } }} wrapper-col={{ span: 24 }}>
                <a-form-item>
                  <a-form-item required label="企业名称" name="travel_agency_name">
                    <a-input style={{ width: '335px' }} v-model:value={form.value.travel_agency_name} disabled={form.value.disabled} />
                  </a-form-item>
                  <a-form-item required label="统一社会信用代码" name="code">
                    <a-input style={{ width: '280px' }} v-model:value={form.value.code} disabled={form.value.disabled} />
                  </a-form-item>
                  <a-form-item required label="企业联系人" name="business_contacts">
                    <a-input style={{ width: '320px' }} v-model:value={form.value.business_contacts} disabled={form.value.disabled} />
                  </a-form-item>
                  <a-form-item wrapper-col={{ span: 12 }} label="企业手机号" name="contract_mobile">
                    <a-input style={{ width: '320px' }} v-model:value={form.value.contract_mobile} maxlength={11} disabled={form.value.disabled} />
                  </a-form-item>
                </a-form-item>
              </a-form>
            }
          </div>
        </div>
      </div>
    )

    const terms_list = reactive({
      list: [
        {
          label: '《客户告知书》',
          download_url: 'client_notice',
        },
        {
          label: '《保险条款》',
          download_url: 'term_rel',
        },
      ],
      term_pact: [],
      checked: false,
    } as any)
    // 点击已读相关协议
    const clickCheked = () => {
      if (form.value.insured_list.filter(x => x.real_name === '').length >= 1) {
        message.error('被保人姓名不能为空');
        return;
      }
      if (form.value.insured_list.filter(x => x.id_no === '').length >= 1) {
        message.error('被保人证件号不能为空');
        return;
      }
      if (form.value.insured_list.filter(x => x.sex === '').length >= 1) {
        message.error('被保人性别不能为空');
        return;
      }
      if (form.value.insured_list.filter(x => x.birthday === '').length >= 1) {
        message.error('被保人出生日期不能为空');
        return;
      }
      if (errorMsgs.value.filter(y => y.error_msg === '被保人姓名长度不能小于2个汉字或4个字母').length > 0) {
        message.error('被保人姓名长度不能小于2个汉字或4个字母')
        return;
      }
      if (errorMsgs.value.filter(y => y.error_msg === '证件号码格式错误').length > 0) {
        message.error('被保人证件号码格式不对,请重新填写')
        return;
      }
      if (errorMsgs.value.filter(y => y.error_msg === '护照支持5-17位大写字母和数字，或纯数字，或纯大写字母').length > 0) {
        message.error('被保人证件号码格式不对,请重新填写')
        return;
      }
      if (errorMsgs.value.filter(y => y.error_msg === '被保人证件号不能重复').length > 0) {
        message.error('被保人证件号重复,请重新填写')
        return;
      }
      terms_list.checked = true;
      $calculatePayMoney({
        product_id: form.value.product_id,
        start_date: form.value.start_date,
        start_hour: 0,
        end_date: form.value.end_date,
        end_hour: 24,
        insured: form.value.insured_list.map(x => {
          return {
            real_name: x.real_name,
            id_type: x.id_type,
            id_no: x.id_no,
            sex: x.sex,
            birthday: x.birthday,
          }
        })
      }).then((res: any) => {
        pay_type.risk_premium = res.data?.sum_premium || 0;
        pay_type.total_premium = res.data?.pay_premium || 0;
      }).catch(() => {
        terms_list.checked = false;
      })
    }

    const agreeRead = (download_url: string) => {
      switch (download_url) {
        case "term_rel":
          TermsRef.value.open(termsState.value);
          break;
        case "client_notice":
          ClientNoticeRef.value.open(noticeTitleState.value, noticeState.value);
          break;
        default:
          window.location.href = download_url;
      }
    }
    const termPactItem = (name: string, content: string) => {
      TermPactRef.value.open(name, content);
    }
    // 协议阅读
    const AgreementRead = () => (
      <div class={styles['agreement-read']}>
        <div class={styles['checkbox']} onClick={() => { clickCheked() }}>
          <CheckSquareFilled class={[styles.icon, terms_list.checked && styles.checked]} />
          <span class={styles.text}>我已认真阅读</span>
        </div>
        <div class={styles['terms-list']}>
          {
            terms_list.list.map((item: any) => (
              <span class={styles['term-text']}
                onClick={() => {
                  agreeRead(item.download_url)
                }}
              >{item.label}</span>
            ))
          }
          {
            terms_list.term_pact.map((item: any) => (
              <span class={styles['term-text']}
                onClick={() => {
                  termPactItem(item.name, item.content)
                }}
              >《{item.name}》</span>
            ))
          }
        </div>
        <span>全部内容并同意</span>
      </div>
    )

    const pay_type = reactive({
      risk_premium: 0,
      total_premium: 0,
      checked: null,
    })

    // 支付方式
    const PayType = () => (
      <div class={styles['pay-type']}>
        <div class={styles['amount-box']}>
          <div class={styles['premium']}>
            <span class={styles['premium-label']}>实付保费：</span>
            <span class={styles['premium-price']}>¥{pay_type.total_premium}</span>
          </div>
          <div class={styles['premium']}>
            <span class={styles['premium-label']}>标准保费：</span>
            <span class={styles['premium-price']}>¥{pay_type.risk_premium}</span>
          </div>
        </div>
        <div class={styles['pay-radio-group']}>
          <a-radio-group
            v-model:value={pay_type.checked}
            name="radioGroup"
            disabled={form.value.insured_list.length === 0}
          >
            <a-radio value={0}>在线支付</a-radio>
            <a-radio value={1}>预缴存支付（余额￥{userStore.user_info.balance}元）</a-radio>
          </a-radio-group>
        </div>
      </div>
    )

    const SmartPasteRef = ref(null as any);
    const BatchImportRef = ref(null as any);


    const errorMsgs = computed(() => {
      let list: any[] = [];
      form.value.insured_list.forEach((x: any) => {
        let error_msg = "";
        error_msg = util.checkName(x);
        error_msg || (error_msg = util.checkIdno(x));
        error_msg || (error_msg = util.checkRepeat(x, form.value.insured_list));
        list.push({
          real_name: x.real_name,
          id_no: x.id_no,
          error_msg,
        })
      })
      return list;
    })

    //删除被保人信息(单条)
    const deleteInsured = (index: number) => {
      if (!(form.value.insured_list.length > 1)) {
        message.error('被保人最少一条');
        return;
      }
      form.value.insured_list.splice((state.page - 1) * 50 + index, 1);
      pay_type.total_premium = 0;
      pay_type.risk_premium = 0;
      terms_list.checked = false;
    }
    //
    const getGroup = () => {
      $getGroup().then((res: any) => {
        window.location.href = res.data?.url || '';
      })
    }
    const disabledDate = (current: any) => {
      return current && current >= dayjs().endOf('day');
    };
    // 被保人表单
    const Insured = () => (
      <div class={styles.insured}>
        <div class={styles['insured-container']}>
          <div class={styles['insured-header']}>
            <div class={styles['insured-title']}>
              <span>被保人信息</span>
            </div>
          </div>
          <div class={styles['insured-toolbar']}>
            <div class={[styles['toolbar-btn'], styles.filled]} onClick={() => { SmartPasteRef.value.open() }}>
              <CopyOutlined class={styles.icon} />
              <span>智能粘贴</span>
            </div>
            <div class={styles['toolbar-btn']} onClick={() => { form.value.insured_list.push({ ..._.cloneDeep(insured_default), key: new Date().getTime() }), terms_list.checked = false }}>
              <UserOutlined class={styles.icon} />
              <span>新增被保险人</span>
            </div>
            <div class={styles['toolbar-btn']} onClick={() => { BatchImportRef.value.open() }}>
              <DownloadOutlined class={styles.icon} style={{ transform: 'rotate(-90deg)' }} />
              <span>批量导入被保险人</span>
            </div>
            <div class={styles['toolbar-btn']} onClick={() => { getGroup() }}>
              <DownloadOutlined class={styles.icon} />
              <span>下载导入模板</span>
            </div>
            {/* <div class={[styles['toolbar-btn'], styles.filled, styles.longer]}>
              <span>身份证识别</span>
            </div>
            <div class={[styles['toolbar-btn'], styles.filled, styles.longer]}>
              <span>护照识别（仅支持中国护照）</span>
            </div> */}
          </div>
          <div class={styles.operate}>
            <div class={styles['operate-container']}>
              <span>被保险人共<span class={styles.count}>{form.value.insured_list.length}</span>人</span>
              <div class={styles['clear-btn']} onClick={() => {
                Modal.confirm({
                  title: '提示',
                  content: '确定删除全部?',
                  okText: '确定',
                  cancelText: '取消',
                  onOk: () => {
                    form.value.insured_list.splice(0, form.value.insured_list.length);
                    terms_list.checked = false;
                    pay_type.total_premium = 0;
                    pay_type.risk_premium = 0;
                  }
                })
              }}>全部删除</div>
            </div>
            <div class={styles['operate-tips']}>提示：如被保人名称中含有生僻字，请使用更为常见的汉字或拼音代替，并确保证件号码正确。理赔时进行批改姓名处理。</div>
          </div>
          <div class={styles['insured-table']}>
            <div class={styles['table-header']}>
              <div class={styles['table-col']}>
                <div class={styles['table-cell']}>序号</div>
              </div>
              <div class={styles['table-col']}>
                <div class={styles['table-cell']}>姓名</div>
              </div>
              <div class={styles['table-col']}>
                <div class={styles['table-cell']}>证件类型</div>
              </div>
              <div class={styles['table-col']}>
                <div class={styles['table-cell']}>证件号码</div>
              </div>
              <div class={styles['table-col']}>
                <div class={styles['table-cell']}>性别</div>
              </div>
              <div class={styles['table-col']}>
                <div class={styles['table-cell']}>出生日期</div>
              </div>
              <div class={styles['table-col']}></div>
            </div>
            {
              form.value.insured_list.length > 0 ? (
                <div class={styles['table-rows']}>
                  {
                    form.value.insured_list.filter((item, index) => (index >= (state.page - 1) * 50) && (index < (state.page * 50))).map((item: any, index: number) => (
                      <div class={styles['table-row']} key={item.key}>

                        <div class={styles['table-col']}>
                          <div class={styles['table-cell']}>{(state.page - 1) * 50 + index + 1}</div>
                        </div>
                        <div class={styles['table-col']}>
                          <div class={styles['table-cell']}>
                            <a-input class={styles.field} v-model:value={item.real_name} />
                          </div>
                        </div>
                        <div class={styles['table-col']}>
                          <div class={styles['table-cell']}>
                            <a-select class={styles.field} v-model:value={item.id_type} dropdownMatchSelectWidth={false}>
                              <a-select-option value="111">身份证</a-select-option>
                              <a-select-option value="07">外国护照</a-select-option>
                              <a-select-option value="414">中国护照</a-select-option>
                              {/* <a-select-option value="港澳回乡证或台胞证">港澳回乡证或台胞证</a-select-option>
                              <a-select-option value="港澳台居民居住证">港澳台居民居住证</a-select-option>
                              <a-select-option value="港澳通行证">港澳通行证</a-select-option>
                              <a-select-option value="往来台湾通行证">往来台湾通行证</a-select-option> */}
                            </a-select>
                          </div>
                        </div>
                        <div class={styles['table-col']}>
                          <div class={styles['table-cell']}>
                            <a-input class={styles.field} v-model:value={item.id_no} style={{ textTransform: 'uppercase' }} onBlur={() => { item.id_no = item.id_no.toUpperCase() }} />
                          </div>
                        </div>
                        <div class={styles['table-col']}>
                          <div class={styles['table-cell']}>
                            <a-select disabled={item.id_type === '111'} class={styles.field} v-model:value={item.sex}>
                              <a-select-option value={1}>男</a-select-option>
                              <a-select-option value={2}>女</a-select-option>
                            </a-select>
                          </div>
                        </div>
                        <div class={styles['table-col']}>
                          <div class={styles['table-cell']}>
                            <a-date-picker disabled={item.id_type === '111'} valueFormat="YYYY-MM-DD" disabled-date={disabledDate} class={styles.field} v-model:value={item.birthday} />
                          </div>
                        </div>
                        <div class={styles['table-col']}>
                          <div class={styles['table-cell']} onClick={() => { deleteInsured(index) }}>
                            <CloseCircleOutlined class={styles['delete-icon']} />
                          </div>
                        </div>
                      </div>
                    ))
                  }
                </div>
              ) : (
                <div class={styles['no-message']}>
                  暂无数据
                </div>
              )
            }
          </div>
          <div class={styles.pagination}>
            <a-pagination v-model:current={state.page} total={form.value.insured_list.length} defaultPageSize={50} />
          </div>
          <div class={styles['error-lines']}>
            {
              errorMsgs.value.map((item: any, index: number) => (
                item.error_msg && <div class={styles['error-line']}>
                  <div class={styles['line-msg']}>
                    姓名：{item.real_name}， 证件号：{item.id_no}
                  </div>
                  <div class={styles['line-error']}>
                    <ExclamationCircleFilled />
                    <span>（第{index + 1}行）{item.error_msg}</span>
                  </div>
                </div>
              ))
            }
          </div>
        </div>
        <div class={styles['text-describe']}>
          <div class={styles.text_content}>
            <p style="font-size: 15px;font-weight: bold;">投保须知：</p>
            <div v-html={text_describe.value}></div>
          </div>
        </div>
        <AgreementRead />
        <PayType />
        <div class={styles['footer-btns']}>
          <div class={styles['submit-btn']} onClick={() => { submit() }}>提交投保单</div>
          <div class={styles['save-btn']} onClick={() => { DraftPopupRef.value.open() }}>保存至草稿箱</div>
        </div>
      </div>
    )

    const PlanEditRef = ref(null as any);
    const ExamplePopupRef = ref(null as any);
    const ClientNoticeRef = ref(null as any);
    const TermsRef = ref(null as any);
    const DraftPopupRef = ref(null as any);
    const TermPactRef = ref(null as any);
    const isClick = ref(false as any);
    const loading = ref(true);
    const loadingText = ref('正在提交保单信息...');
    const timeout = ref(null as any);
    const timeoutTwo = ref(null as any);

    // const zip = (str: string) => {
    //   let binaryString: any = pako.gzip(encodeURIComponent(str))
    //   return btoa(binaryString);
    // }

    //提交保单
    const submit = async () => {
      let param = {
        sex: '',
        id_type: '',
        realname: '',
        idcard: '',
        mobile: '',
      }
      let list = form.value.insured_list.filter(x => x.id_type === '07' || x.id_type === '414').filter(x => !validateInstance.test(x.id_no, "passport"))
      console.log(list)
      if (!form.value.realname && form.value.id_type === 111) {
        message.error('投保人姓名为空');
        return;
      }
      if (!validateInstance.test(form.value.realname, "Chinese") && form.value.id_type === 111) {
        message.error('投保人姓名不是汉字，请重新输入')
        return;
      }
      if (!form.value.mobile && form.value.id_type === 111) {
        message.error('联系人手机号为空');
        return;
      }
      if (!validateInstance.test(form.value.idcard, "idcard") && form.value.id_type === 111) {
        message.error('投保人证件号格式不正确');
        return;
      }
      if (form.value.insured_list.filter(x => x.real_name === '').length >= 1) {
        message.error('被保人姓名不能为空');
        return;
      }
      if (form.value.insured_list.filter(x => !validateInstance.test(x.real_name, "Chinese")).length >= 1) {
        message.error('被保人姓名应该为汉字，请重新输入');
        return;
      }
      if (form.value.insured_list.filter(x => x.id_type === '07' || x.id_type === '414').filter(x => !validateInstance.test(x.id_no, "passport")).length >= 1) {
        message.error('被保人证件格式不正确');
        return;
      }
      if (form.value.insured_list.filter(x => x.id_no === '').length >= 1) {
        message.error('被保人证件号不能为空');
        return;
      }
      if (form.value.id_type === 0) {
        form.value.idcard = form.value.insured_list[0].id_no;
      }
      let sex = Number(form.value.idcard.slice(16, 17));
      param.sex = String((sex % 2 === 1) ? 1 : 2);
      console.log(param.sex, '性别');
      if (form.value.id_type === 0) {
        param.id_type = form.value.insured_list[0].id_type;
        param.realname = form.value.insured_list[0].real_name;
        param.idcard = form.value.insured_list[0].id_no;
        param.sex = form.value.insured_list[0].sex;
        param.mobile = userStore.user_info.mobile;
        // form.value.realname = form.value.insured_list[0].real_name;
        // form.value.idcard = form.value.insured_list[0].id_no;
        // form.value.mobile = userStore.user_info.mobile;
        // console.log(form.value.business_contacts, form.value.idcard);
        console.log(param)
      }
      if (form.value.id_type === 111) {
        param.id_type = '111';
        param.realname = form.value.realname;
        param.idcard = form.value.idcard;
        param.mobile = form.value.mobile;
      }
      if (form.value.id_type === 989) {
        param.id_type = '989';
        param.idcard = form.value.code;
        param.realname = form.value.travel_agency_name;
        param.mobile = form.value.contract_mobile;
      }
      if (isClick.value === true) return;
      if (!terms_list.checked) {
        message.error('请阅读相关文件')
        return;
      }
      if (pay_type.checked === null) {
        message.error('请选择支付方式')
        return;
      }
      if (pay_type.checked === 1 && Number(userStore.user_info.balance) < Number(pay_type.total_premium)) {
        message.error('余额不足，请充值')
        return;
      }
      isClick.value = true;
      loading.value = false;
      console.log(form.value.insured_list)
      const [screenErr, screenRes] = await saveScreenRecord();
      if (screenErr) {
        message.error("记录提交失败,请重新提交!");
        isClick.value = false;
        loading.value = true;
        return;
      }
      timeout.value = setTimeout(() => {
        $creatGroup({
          product_id: Number(form.value.product_id),
          start_date: form.value.start_date,
          start_hour: 0,
          end_date: form.value.end_date,
          end_hour: 24,
          tour_route: form.value.tour_route,
          tour_group_no: form.value.tour_group_no,
          applicant: {
            id_type: param.id_type,
            sex: Number(param.sex),
            id_no: param.idcard,
            contract_person: param.realname,
            contract_mobile: Number(param.mobile),
            business_contacts: form.value.business_contacts,
          },
          insured: form.value.insured_list.map(x => {
            return {
              real_name: x.real_name,
              id_type: x.id_type,
              id_no: x.id_no,
              sex: x.sex,
              birthday: x.birthday,
            }
          }),
          pay_type: 'BALANCE',
          screen_record: screenRes.domain + screenRes.objectName,
        }).then((res: any) => {
          loadingText.value = '正在支付';
          let order_no = res?.data?.order_no || "";
          let return_url = '';
          if (pay_type.checked === 0) {   //在线支付
            $onlinePay({
              out_trade_no: res?.data?.out_trade_no || "",
              pay_type: "sfypay",
              app_type: "pc",
              return_url: `${process.env.VUE_APP_PAY_RETURN_URL}?order_no=${order_no}`
            }).then((res: any) => {
              const payObj = res.data?.data || {};
              loading.value = true;
              window.location.href = payObj;
            }).catch(() => {
              isClick.value = false;
              loading.value = true;
            })
          } else {
            $pay({                      //余额支付
              out_trade_no: res?.data?.out_trade_no || "",
              pay_type: "BALANCE",
            }).then((payRes: any) => {
              loading.value = true;
              message.success("支付成功!");
              eventBus.payed.emit();
              timeoutTwo.value = setTimeout(() => {
                router.push(`/userCenter/index/orderDetail?order_no=${order_no}`);
                const dom: any = document.getElementById("app");
                dom.scrollTop = 0;
                isClick.value = false;
              }, 1000)
            }).catch(() => {
              isClick.value = false;
              loading.value = true;
            })
          }
        }).catch(() => {
          terms_list.checked = false;
          pay_type.total_premium = 0;
          pay_type.risk_premium = 0;
          isClick.value = false;
          loading.value = true;
        })
      }, 1000)
    }

    //特别声明
    const statementReadClose = () => {
      statement_read.value = true;
    }

    onUnmounted(() => {
      clearTimeout(timeout.value);
      clearTimeout(timeoutTwo.value);
    })

    return () => (
      <>
        <div class={styles.AccidentInsurePage}>
          <div class={styles.groupInsure}>
            <div class={styles['insure-content-left']}>
              <div class={styles['insure-header']}>
                <img src={imgPath("/safe.png")} />
                <span>为了保障您的权益，请填写真实有效的信息。您填写的内容仅供投保使用，对于您的信息我们会严格保密。</span>
              </div>
              <div class={styles['insure-container']}>
                <div class={styles['policyholder-information']}>
                  <div class={styles['groupaccidentText']}>
                    <div class={styles['plan']}>保险方案</div>
                    <div class={styles['edit-btn']} onClick={() => PlanEditRef.value.open({
                      start_date: form.value.start_date,
                      end_date: form.value.end_date,
                      count: form.value.count,
                      tour_route: form.value.tour_route,
                      tour_group_no: form.value.tour_group_no,
                    })}>
                      <EditOutlined class={styles.icon} />
                      <span>修改</span>
                    </div>
                  </div>
                  <div class={styles['insure-date1']}>
                    <div class={styles['insure-date1-rows']}>
                      <div class={styles['insure-date1-row']}>
                        <div class={styles['insure-date1-col']}>
                          <div class={styles['col-label']}>保险期限：</div>
                          <div class={[styles['col-value'], styles['long-field']]}>
                            <span>{form.value.start_date}</span>
                            <span style={{ margin: '0 5px' }}>起 至</span>
                            <span>{form.value.end_date}</span>
                            <span style={{ margin: '0 10px' }}>共{during_date.value}天</span>
                          </div>
                        </div>
                        <div class={styles['insure-date1-col']}>
                          <div class={styles['col-label']}>保险份数：</div>
                          <div class={styles['col-value']}>{form.value.count}份</div>
                        </div>
                      </div>
                      <div class={styles['insure-date1-row']}>
                        <div class={styles['insure-date1-col']}>
                          <div class={styles['col-label']}>旅游路线：</div>
                          <div class={[styles['col-value'], styles['long-field']]}>
                            <span>{form.value.tour_route}</span>
                          </div>
                        </div>
                        <div class={styles['insure-date1-col']}>
                          <div class={styles['col-label']}>旅游团编号：</div>
                          <div class={styles['col-value']}>{form.value.tour_group_no}</div>
                        </div>
                      </div>
                    </div>
                    <div class={styles['remind-text-box']}>
                      <div class={styles['remind-text']}>
                        {/* <div class={styles['remind-text-row']}>
                          <span class={styles.text} style={{ margin: "0 10px" }}>T+1小时：指所有当日投保、当日起保的保单（即保险期间开始于投保日当日的保单），支付保费成功后，最早起保时间为支付时间延后一小时。</span>
                        </div>
                        <div class={styles['remind-text-row']}>
                          <BellFilled class={styles.icon} />
                          <span class={styles.text}>所有当日投保、当日起保的保单（即保险期间开始于投保日当日的保单），航班延误保险责任或旅程延误保险责任的保险责任起期为保险单载明的保险期间的开始时间的次日零时</span>
                        </div> */}
                        <div class={styles['remind-text-row']}>
                          <BellFilled class={styles.icon} />
                          <span class={styles.text}>本保险方案承保地域：限中国境内（不含香港、澳门、台湾地区）</span>
                        </div>
                      </div>
                    </div>
                  </div>
                  <Applicant />
                </div>
                <Insured />
              </div>
            </div>
            <div class={styles['insure-content-right']}>
              <div class={styles.plan}>{form.value.name}</div>
              <div class={styles['single-information']}>
                <div class={styles['information-item']}>
                  <span class={styles['company']}>出单公司：中国人民财产保险股份有限公司</span>
                </div>
                <div class={styles['information-item']}>
                  <LIcon type="icon-rili" class={styles.icon} />
                  <span>起保日期: {form.value.start_date}</span>
                </div>
                <div class={styles['information-item']}>
                  <LIcon type="icon-calendar-finish" class={styles.icon} />
                  <span>止保日期: {form.value.end_date}</span>
                </div>
                <div class={styles['information-item']}>
                  <LIcon type="icon-shizhong" class={styles.icon} />
                  <span>保险期间: {during_date.value}天</span>
                </div>
                <div class={styles['information-item']}>
                  <LIcon type="icon-renyuan" class={styles.icon} />
                  <span>人数: {form.value.insured_list.length}</span>
                </div>
                <div class={styles['information-item']}>
                  <LIcon type="icon-fenshu" class={styles.icon} />
                  <span>份数: {form.value.count}份</span>
                </div>
              </div>
              <div class={styles['insure-money']}>
                <span>保费合计:</span>
                <span class={styles.money}>￥{pay_type.total_premium}</span>
              </div>
              <div class={styles['slide-payType']}>
                <div class={styles['pay-radio-group']}>
                  <a-radio-group
                    v-model:value={pay_type.checked}
                    name="radioGroup"
                    disabled={form.value.insured_list.length === 0}
                  >
                    <a-radio value={0} style={{ marginBottom: '8px' }}>在线支付</a-radio>
                    <a-radio value={1}>预缴存支付(余额￥{userStore.user_info.balance}元)</a-radio>
                  </a-radio-group>
                </div>
              </div>
              <div class={styles.commitBtn}>
                <div class={styles['submit-btn']} onClick={() => { submit() }}>
                  提交投保单
                </div>
                <div class={styles['save-btn']} onClick={() => { DraftPopupRef.value.open() }}>
                  保存至草稿箱
                </div>
              </div>
            </div>
          </div>
        </div>

        {
          statement_read.value ||
          (
            <div class={styles['statement-floating']}>
              <div class={styles['statement-card']}>
                <div class={styles['statement-card-header']}>
                  <span class={styles.title}>特别声明</span>
                  <LIcon class={styles['delete-icon']} type="icon-delete-x" onClick={() => { statement_read.value = true }} />
                </div>
                <div class={styles['statement-card-content']}>
                  本产品的销售主体和保险经纪人为中联金安保险经纪有限公司，负责为投保人提供协助投保、协助理赔、投保咨询等保险经纪服务。本产品承保公司为中国人民财产保险股份有限公司，负责提供承保、理赔等保险服务。中国人民财产保险股份有限公司官网：https://property.picc.com/  全国统一客服电话：95518
                </div>
                <div class={styles['statement-card-footer']}>
                  <div class={styles['statement-btn']} onClick={() => { statementReadClose() }}>确 定</div>
                </div>
              </div>
            </div>
          )
        }
        {
          loading.value ||
          (
            <Teleport to="body">
              <div class={styles['statement-floating']}>
                <div class={styles['loading-box']}>
                  <div class={styles.content}>
                    <LoadingOutlined class={styles.icon} />
                    <span class={styles.text}>{loadingText.value}</span>
                  </div>
                </div>
              </div>
            </Teleport>
          )
        }
        <PlanEdit ref={PlanEditRef} onConfirm={(e) => {
          form.value.start_date = e.start_date || '';
          form.value.end_date = e.end_date || '';
          form.value.count = e.count;
          form.value.tour_route = e.tour_route;
          form.value.tour_group_no = e.tour_group_no;
          terms_list.checked = false;
          pay_type.total_premium = 0;
          pay_type.risk_premium = 0;
        }} />
        <ExamplePopup ref={ExamplePopupRef} />
        <ClientNotice ref={ClientNoticeRef} />
        <Terms ref={TermsRef} />
        <SmartPaste ref={SmartPasteRef} onConfirm={(e) => {
          if (form.value.insured_list.length === 0 || (form.value.insured_list.length === 1 && !form.value.insured_list[0].id_no)) {
            form.value.insured_list = e.map((x: any) => {
              return {
                key: new Date().getTime(),
                ...x
              }
            });
            return;
          }
          e.forEach((x: any) => {
            if (!form.value.insured_list.map(x => x.id_no).includes(x.id_no)) {
              form.value.insured_list.push({
                key: new Date().getTime(),
                ...x
              })
            }
          })
        }} />
        <BatchImport ref={BatchImportRef} onConfirm={(e) => {
          console.log(e[0].originFileObj)
          let forms = new FormData();
          forms.set('file', e[0].originFileObj);
          $importPeople(forms).then((res: any) => {
            let list: any = [];
            list = list.concat(form.value.insured_list).concat(res.data.map((x: any) => {
              return {
                real_name: x.name,
                id_type: x.id_type,
                id_no: x.id_no,
                sex: x.sex,
                birthday: x.birthday,
              }
            }));
            let arr: any[] = [];
            list.forEach((x: any) => {
              if (!arr.map(y => y.id_no).includes(x.id_no)) {
                arr.push(x);
              }
            })
            form.value.insured_list = arr;
          })
        }} />
        <DraftPopup ref={DraftPopupRef} />
        <TermPact ref={TermPactRef} />
      </>
    )
  }
})